"""
用户信息表
@author:yczha
"""

from sqlalchemy import Column, String, Integer

from src.models.db import db
from src.api.check_token import check_token


class User(db.Models):
    """用户表"""
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    username = Column(String(100), unique=True)
    password = Column(String(100), default='')
    token = Column(String(1000), default='')

    def __repr__(self):
        return f'<User {self.username}>'

    @staticmethod
    def get_user(require_login=False):
        """获取user，根据是否要求登陆进行校验"""
        with db.Session() as sess:
            users = sess.query(User).all()
            user = users[0] if users else None
            if not user:
                return None
            if not require_login:
                return user
            elif user.token and check_token(user.token) == 1000:
                return user
            return None

    @staticmethod
    def update_user(user_obj):
        """更新User"""
        with db.Session() as sess:
            user = User.get_user() or User(username=user_obj['username'], password=user_obj['password'])
            for key, value in user_obj.items():
                if key not in ['username', 'password', 'token']:
                    continue
                user.__setattr__(key, value)
            sess.add(user)
            sess.commit()
            return user


db.init_db()
